<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 收入
 *
 */
class XBjbody extends Backend
{
    /**
     * XBjbody模型对象
     * @var \app\admin\model\XBjbody
     */
    protected $model = null;
    protected $head= null;
    protected $cost=null;
    protected $code=null;
    protected $line=null;
    protected $quickSearchField = ['ID'];
//    protected $noNeedLogin      = ['add','del','edit'];
    protected $noNeedLogin      = ['*'];

    protected $defaultSortField = 'ID,desc';

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XBjbody;
        $this->line = new \app\admin\model\XBjline;
        $this->head =new \app\admin\model\XBjhead();
        $this->code =new \app\admin\model\Codelib();
        $this->cost=new \app\admin\model\XBjcost();
    }


    /**
     * 查看
     * type 1常规2线路
     * gstype 1客户/2供应商
     * bjno 报价号
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        //判断是常规还是线路
        $get=$this->request->get();
//        $get=['type'=>1,'bjno'=>'2104YJ0001','gstype'=>2];
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $data='';
        if($get['gstype']==1){
            if($get['type']==1){

                $sql="SELECT
                        CODELIB.CODENAME,
                        X_BJLINE.ID,
                        X_BJBODY.ID as bid ,
                        X_BJBODY.PRICETYPE,
                        X_BJBODY.UNITPRICE,
                        X_BJBODY.MONEYTYPE,
                        X_BJBODY.TAXRATE,
                        X_BJBODY.NOTAXPRICE,
                    (CASE
                            WHEN X_BJBODY.ITEMCODE= 'ZXF' THEN
                            '租期' ELSE '免费' 
                        END) AS TYPE ,
                        X_BJBODY.TRANSDAYS,
                        CODELIB.REMIND,
                        X_BJBODY.NOTE 
                    FROM
                      x_bjline as X_BJLINE,
                        x_bjbody as X_BJBODY,
                        codelib as  CODELIB
                    WHERE
                        X_BJLINE.ID= X_BJBODY.LINEID 
                        AND X_BJLINE.LOADPLACE IS NULL 
                        AND X_BJLINE.BJNO= '$get[bjno]' 
                        AND X_BJBODY.ITEMCODE= CODELIB.CODE 
                        AND CODELIB.CODETYPE= 'cgbj'";
                $res=Db::query("$sql");
                $id=$this->line->where(['BJNO'=>$get['bjno']])->where("LOADPLACE IS NULL")->value('id');
                //判断是否有常规线路
                if($res){
                    $data= [
                        'id'=>$id,
                        'list'   => $res,
                        'total'  => count($res),
                        'remark' => get_route_remark(),
                    ];
                }else{
                    $data= [
                        'id'=>$id,
                        'list'   => '',
                        'total'  =>'',
                        'remark' => '',
                    ];
                }


            }else{
                $res = $this->line
                    ->field('ID,LOADPLACE,DISPLACE,BJNO')
                    ->with('body')
                    ->alias($alias)
                    ->where($where)
                    ->where(['BJNO'=>$get['bjno']])
                    ->where('LOADPLACE','<>',' ')
                    ->order($order)
//                    ->fetchSql()->select();
                    ->paginate($limit);
//                var_dump($res);die;
                $code=$this->code->where('codetype','itemcode')->column('CODENAME','CODE');
                foreach ($res as &$re) {
                    foreach ($re['body'] as $k=>&$item) {
                        if (isset($code[$item['ITEMCODE']])) {
                            $item['ITEMCODE'] = $code[$item['ITEMCODE']];
                        }
                    }
                    $re['day']=Db::query("select  sum(transdays) as day from x_bjcost where lineid='$re[ID]'  and bjno='$get[bjno]'   and costtype<>'GXZLCB' ")[0]['day'];
                    $re['rmb_costs']=Db::query("select  sum(case when costtype='GXZLCB' then unitprice * transdays else unitprice end) as costs from x_bjcost where  lineid='$re[ID]' and bjno='$get[bjno]' and moneytype='RMB' ")[0]['costs'];
                    $re['usd_costs']=Db::query("select  sum(case when costtype='GXZLCB' then unitprice * transdays else unitprice end) as costs from x_bjcost where  lineid='$re[ID]' and bjno='$get[bjno]' and moneytype='USD' ")[0]['costs'];

                    $re['rmb_price']=Db::query("select  sum(case when  itemcode='ZXF' then  unitprice*transdays else  unitprice end) as price from x_bjcost where lineid='$re[ID]' and bjno='$get[bjno]' and moneytype='RMB'")[0]['price'];
                    $re['usd_price']=Db::query("select  sum(case when  itemcode='ZXF' then  unitprice*transdays else  unitprice end) as price from x_bjcost where lineid='$re[ID]' and bjno='$get[bjno]' and moneytype='USD'")[0]['price'];
                    $re['profit']=Db::query("select  sum(case when itemcode='ZXF' then unitprice*transdays*currentrate.rate else unitprice*currentrate.rate end) as one  from x_bjbody,currentrate where x_bjbody.moneytype=currentrate.moneytype and lineid='$re[ID]' and bjno='$get[bjno]'")[0]['one']  -  Db::query("select  sum(case when costtype='GXZLCB' then unitprice*transdays*currentrate.rate else unitprice*currentrate.rate end) as two from x_bjcost,currentrate  where  x_bjcost.moneytype=currentrate.moneytype and lineid='$re[ID]' and bjno='$get[bjno]'")[0]['two']      ;
                    $re['net_profit']=Db::query("select  sum(case when itemcode='ZXF' then notaxprice*transdays*currentrate.rate else notaxprice*currentrate.rate end) as one from x_bjbody,currentrate where x_bjbody.moneytype=currentrate.moneytype and lineid='$re[ID]'  and bjno='$get[bjno]'")[0]['one']-Db::query("select  sum(case when costtype='GXZLCB' then notaxprice*transdays*currentrate.rate else notaxprice*currentrate.rate end) as two from x_bjcost,currentrate  where  x_bjcost.moneytype=currentrate.moneytype and lineid='$re[ID]'  and bjno='$get[bjno]'")[0]['two'];
                    if($re['net_profit']!=0)  $re['margin']=round(100* ($re['profit'] / $re['net_profit']),2).'%';
                    else $re['margin']=0;
                }
                $data= [
                    'list'   => $res->items(),
                    'total'  => $res->total(),
                    'remark' => get_route_remark(),
                ];
            }
        }else{
            $res=$this->model->where('BJNO',$get['bjno'])->select();
            $data= [
                'list'   => $res,
                'total'  => count($res),
                'remark' => get_route_remark(),
            ];
        }




        $this->success('',$data);
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param('bid');
        if(!$id){
            $id  = $this->request->param($this->model->getPk());
        }
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 供应商报价参考
     */
    public function gys(){
        $corp=$this->request->get('CORP');
        $where='';
        if($corp){
            $where=" and x_bjhead.CORP=$corp";
        }
        $data=Db::query("select x_bjbody.id,x_bjhead.BJNO,x_bjbody.ITEMCODE,x_bjhead.corp,x_bjbody.txplace,x_bjbody.loadplace,x_bjbody.displace,x_bjbody.returnplace,x_bjbody.isdg,x_bjbody.pricetype,x_bjbody.transdays,x_bjbody.unitprice,x_bjbody.moneytype,x_bjbody.taxrate,x_bjbody.notaxprice,x_bjbody.note,x_bjhead.enddate from x_bjhead,x_bjbody where x_bjhead.bjno=x_bjbody.bjno and x_bjhead.corptype='供应商' and x_bjhead.bjstatus='1' $where ");
        $this->success('',$data);
    }
    public function day(){
        $line=$this->request->get('line');
        $day=$this->cost->where('LINEID','2')->sum('TRANSDAYS');
        $this->success('',$day);
    }
}